<template>
    <div>
        <div class="table-title">
            <h3>用户信息表</h3>
        </div>
        <div class="user-show">
            <div class="user-table">
                <div class="user-table-utils">
                    <div>
                        <el-input placeholder="请输入查询内容" v-model="searchContent" class="input-with-select">
                            <el-select v-model="searchItem" slot="prepend" placeholder="请选择查询项">
                                <el-option v-for="item in searchItems" :key="item.value" :label="item.label"
                                    :value="item.value" />
                                <el-option v-if="userRole" label="角色权限" value="role" />
                            </el-select>
                            <el-button slot="append" icon="el-icon-search" @click="handleSearch" />
                        </el-input>
                    </div>
                    <div>
                        <el-button  v-if="userRole" type="success" plain icon="el-icon-plus" @click="addUser">新增用户</el-button>
                    </div>
                </div>
                <el-table :data="tableData" border style="width: 100%" v-loading="tableLoading">
                    <el-table-column prop="workId" label="学号/工号" width="180">
                    </el-table-column>
                    <el-table-column prop="name" label="姓名" width="180">
                    </el-table-column>
                    <el-table-column prop="username" label="用户名">
                    </el-table-column>
                    <el-table-column prop="post" label="职位">
                    </el-table-column>
                    <el-table-column prop="college" label="学院">
                    </el-table-column>
                    <el-table-column v-if="userRole" prop="role" label="角色">
                        <template slot-scope="scope">
                            <div slot="reference" class="name-wrapper">
                                <el-tag v-if="scope.row.role === '普通用户'" size="medium">{{ scope.row.role }}</el-tag>
                                <el-tag v-else size="medium" type="warning">{{ scope.row.role }}</el-tag>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="userRole" fixed="right" label="操作" width="100">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" style="margin-right: 10px;"
                                @click="handleEdit(scope.row)">编辑</el-button>

                            <el-popconfirm title="确定删除吗？" @confirm="handleDel(scope.row)">
                                <el-button :loading="delLoading" slot="reference" type="text" size="small">删除</el-button>
                            </el-popconfirm>

                        </template>
                    </el-table-column>
                </el-table>
                <div class="user-pagination">
                    <el-pagination background small layout="prev, pager, next" :total="pagination.total"
                        :page-size="pagination.pageSize" :current-page="pagination.current"
                        @current-change="handleCurrentChange" />
                </div>
            </div>
        </div>

        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

                <el-form-item label="姓名" prop="name">
                    <el-input type="text" v-model="ruleForm.name" autocomplete="off" clearable />
                </el-form-item>

                <el-form-item label="工号/学号" prop="workId">
                    <el-input type="text" v-model="ruleForm.workId" autocomplete="off" clearable />
                </el-form-item>

                <el-form-item label="用户名" prop="username">
                    <el-input type="text" v-model="ruleForm.username" autocomplete="off" clearable />
                </el-form-item>

                <el-form-item label="学院" prop="college">
                    <el-select v-model="ruleForm.college" filterable placeholder="请选择学院">
                        <el-option v-for="item in colleges" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="职位" prop="post">
                    <el-select v-model="ruleForm.post" placeholder="请选择职位">
                        <el-option label="学生" value="student"></el-option>
                        <el-option label="教师" value="teacher"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="权限" prop="role">
                    <el-select v-model="ruleForm.role" placeholder="请选择权限">
                        <el-option label="普通用户" value=1 />
                        <el-option label="管理员" value=0 />
                    </el-select>
                </el-form-item>

            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="handleExit">取 消</el-button>
                <el-button type="success" plain  @click="handleSubmit" :loading="editLoading">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import apis from '@/utils/api';
import request from '@/utils/requestMethod';
import './style.less';
import ifAdmin from '@/utils/judgeAdmin';
import { Message } from 'element-ui';

export default {
    name: 'userInfo',
    mounted() {
        this.getUserInfo();
        this.fetchColleges();
        this.userRole = ifAdmin();
    },
    data() {
        /**
     *  对姓名进行校验
     */
        const validateName = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入姓名'));
            } else if (value.length > 20) {
                callback(new Error('姓名不能超过20位'));
            } else {
                callback();
            }
        };

        /**
         *  对工号或学号进行校验
         */
        const validateUsername = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入用户名'));
            } else if (value.length > 20) {
                callback(new Error('用户名不能超过20位'));
            } else {
                callback();
            }
        };

        /**
         *  对用户名进行校验
         */
        const validateWorkId = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入工号或学号'));
            } else if (value.length > 20) {
                callback(new Error('工号或学号不能超过20位'));
            } else {
                callback();
            }
        };

        /**
         *  对学院进行校验
         */
        const validateCollege = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请选择学院'));
            } else {
                callback()
            }
        };

        /**
         *  对职位进行校验
         */
        const validatePost = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请选择职位'));
            } else {
                callback()
            }
        };

        /**
         *  对权限进行校验
         */
         const validateRole = (rule, value, callback) => {
            if (value === '' || value === undefined) {
                callback(new Error('请选择权限'));
            } else {
                callback()
            }
        };

        return {
            dialogVisible: false,
            tableLoading: false,
            delLoading: false,
            editLoading: false,
            tableData: [],
            userRole: false,
            searchItem: '',
            dialogTitle: '新增用户',
            searchItems: [
                {
                    label: '全部',
                    value: 'all'
                },
                {
                    label: '学号/工号',
                    value: 'workId'
                },
                {
                    label: '姓名',
                    value: 'name'
                },
                {
                    label: '用户名',
                    value: 'username'
                },
                {
                    label: '职位',
                    value: 'post'
                },
                {
                    label: '学院',
                    value: 'college'
                }
            ],
            searchContent: '',
            pagination: {
                current: 1,
                pageSize: 10,
                total: 0
            },
            editRow: {},
            ifSave: true,
            ruleForm: {
                name: '',
                workId: '',
                username: '',
                college: '',
                post: '',
                role: 1
            },
            ifSearch: false,
            colleges: [],
            rules: {
                name: [
                    { validator: validateName, trigger: 'blur' }
                ],
                workId: [
                    { validator: validateWorkId, trigger: 'blur' }
                ],
                username: [
                    { validator: validateUsername, trigger: 'blur' }
                ],
                college: [
                    { validator: validateCollege, trigger: 'blur' }
                ],
                post: [
                    { validator: validatePost, trigger: 'blur' }
                ],
                role: [
                    { validator: validateRole, trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        /**
         * 获取用户信息
         */
        getUserInfo() {
            this.tableLoading = true;
            const {
                pagination: {
                    current,
                    pageSize
                }
            } = this;
            request(apis.fetchUserInfo + `?pageSize=${pageSize}&current=${current}`).then(res => {
                const {
                    objects,
                    total
                } = res.data;
                this.pagination.total = total;
                objects.forEach(item => {
                    item.post = item.post === 'student' ? '学生' : '教师';
                    item.role = item.role === 1 ? '普通用户' : '管理员';
                });

                this.tableData = objects;
            }).finally(() => {
                this.tableLoading = false;
            }).catch(() => {
                this.tableLoading = false;
            });
        },

        /**
         *  获取所有学院信息
         */
        fetchColleges() {
            request(apis.fetchCollegeList).then(res => {
                const {
                    objects
                } = res.data;

                if (objects.length > 0) {
                    const colleges = [];
                    objects.forEach(item => {
                        const tempObj = {
                            label: item.name,
                            value: item.name
                        };
                        colleges.push(tempObj);
                    })
                    this.colleges = colleges;
                }
            })
        },

        /**
         *  点击新增按钮事件
         */
        addUser() {
            this.ifSave = true;
            this.dialogVisible = true;
            this.dialogTitle = '新增用户';
            this.ruleForm = {
                name: '',
                workId: '',
                username: '',
                college: '',
                post: ''
            };
        },

        /**
         * 点击编辑按钮事件
         */
        handleEdit(row) {
            this.ifSave = false;
            this.dialogVisible = true;
            this.editRow = row;
            this.ruleForm = row;
            this.dialogTitle = '编辑用户信息'
        },

        /**
         * 点击取消按钮事件
         */
        handleExit() {
            this.dialogVisible = false;
            this.editLoading = false;
        },

        /**
         *  处理表单提交事件
         */
        handleSubmit() {
            this.$refs['ruleForm'].validate((valid) => {
                const {
                    ruleForm,
                    editRow,
                    ifSave
                } = this;

                if (valid) {
                    this.editLoading = true;
                    if (!ifSave) {

                        if (editRow.post === '学生' || editRow.post === 'student') {
                            editRow.post = 'student';
                        }
                        if (editRow.post === '教师' || editRow.post === 'teacher') {
                            editRow.post = 'teacher';
                        }
                    }

                    request(apis.editOrSaveUser, {
                        method: 'POST',
                        body: ifSave ? ruleForm : editRow
                    }).then(res => {
                        const {
                            objects,
                            message
                        } = res.data;
                        if (objects) {
                            Message.success(message);
                            this.dialogVisible = false;
                        } else {
                            const errMessage = ifSave ? '新增用户失败' : '修改用户信息失败';
                            Message.warning(errMessage);
                        }
                    }).finally(() => {
                        this.getUserInfo();
                        this.editLoading = false;
                    }).catch(() => {
                        this.editLoading = false;
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });


        },

        /**
         * 处理表格删除事件
         */
        handleDel(row) {
            this.delLoading = true;
            row.post = row.post === '学生' ? 'student' : 'teacher';
            row.role = row.role === '普通用户' ? 0 : 1;
            request(apis.delUser, {
                method: 'POST',
                body: row
            }).then(res => {
                const {
                    objects,
                    message
                } = res.data;
                if (objects) {
                    Message.success(message);
                }
            }).finally(() => {
                this.delLoading = false;
                this.getUserInfo();
            }).catch(() => {
                Message.error("删除失败");
                this.delLoading = false;
            })
        },

        /**
         * 处理翻页事件
         */
        handleCurrentChange(value) {
            this.pagination.current = value;
            if (this.ifSearch) {
                this.handleSearch();
            } else {
                this.getUserInfo();
            }
        },
        handleClose(done) {
            done();
        },

        /**
         *  处理搜索事件
         */
        handleSearch() {
            this.ifSearch = true;
            const {
                searchItem,
                searchContent,
                pagination: {
                    current,
                    pageSize
                }
            } = this;

            if (searchItem === 'all') {
                this.getUserInfo();
                this.searchContent = '';
                this.searchItem = '';
                this.ifSearch = false;
            } else {
                if (searchItem === '') {
                    Message.warning('请输入搜索项');
                }
                if (searchContent === '') {
                    Message.warning('请输入搜索内容');
                }
            }

            if (searchContent !== '' && searchItem !== '' && searchItem !== 'all') {
                let content = searchContent;
                if (searchItem === 'post') {
                    if (searchContent === '学生') {
                        content = 'student';
                    }
                    if (searchContent === '教师') {
                        content = 'teacher';
                    }
                }
                const body = {
                    searchItem,
                    content,
                    current,
                    pageSize
                }
                this.tableLoading = true;
                request(apis.searchUser, {
                    method: 'POST',
                    body
                }).then(res => {
                    const {
                        objects,
                        message,
                        total
                    } = res.data;

                    objects.forEach(item => {
                        item.post = item.post === 'student' ? '学生' : '教师';
                        item.role = item.role === 1 ? '普通用户' : '管理员';
                    });

                    this.pagination.total = total;
                    this.tableData = objects;
                    Message.success(message);

                }).finally(() => {
                    this.tableLoading = false;
                }).catch(() => {
                    this.tableLoading = false;
                    Message.error('搜索失败');
                })
            }
        }
    }
}
</script>